package com.common.help.test16;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class NIOClient {

	private SocketChannel client;
	private SocketAddress remote = new InetSocketAddress("localhost", 8080);
	private Selector selector;
	private ByteBuffer dst = ByteBuffer.allocate(1024);
	private ByteBuffer src = ByteBuffer.allocate(1024);
	public NIOClient() throws IOException {
		client = SocketChannel.open();
		client.configureBlocking(false);//非阻塞
		client.connect(remote);
		selector = Selector.open();
		client.register(selector, SelectionKey.OP_CONNECT);
	}

	private void session() throws IOException {
		
		if(client.isConnectionPending()){
			client.finishConnect();
			client.register(selector, SelectionKey.OP_WRITE);
			
			System.err.println("请填写你的姓名进行登记:");
			
			Scanner sc = new Scanner(System.in);
			while(sc.hasNext()){
				String name = sc.next();
				if("".equals(name)){
					continue;
				}else if("exit".equals(name)){
					System.exit(0);
				}
				process(name);
			}
		}
		
		
	}
	
	private void process(String name) throws IOException {
		Boolean flag = true;
		while(flag){
			int count = selector.select();
			if(count==0){
				continue;
			}
			Set<SelectionKey> keys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = keys.iterator();
			while(iterator.hasNext()){
				SelectionKey key = iterator.next();
				if(key.isWritable()){
					src.clear();
					src.put(name.getBytes());
					src.flip();
					client.write(src);
					client.register(selector, SelectionKey.OP_READ);
				}else if(key.isReadable()){
					dst.clear();
					int len = client.read(dst);
					dst.flip();
					if(len>0){
						System.out.println(new String(dst.array(),0,len));
					}
					client.register(selector, SelectionKey.OP_WRITE);
					flag = false;
				}
			}
		}
		
	}

	public static void main(String[] args) throws IOException {
		new NIOClient().session();
	}

}
